//
//  GKNovelView.swift
//  MySwiftObject
//
//  Created by wangws1990 on 2018/9/10.
//  Copyright © 2018 wangws1990. All rights reserved.
//

import UIKit

class GKNovelView: BaseView {
    var newRect :CGRect? = nil
    deinit {
        debugPrint("BBookView")
    }
    var progress : CGFloat?{
        didSet{
            guard let item = self.progress else { return }
            self.backgroundColor = UIColor.clear
            let size = BaseMacro.appFrame().size
            let height =  size.height - item * size.height
            let rect = CGRect(x: 0, y: 0, width: size.width, height: height)
            self.newRect = rect
            self.setNeedsDisplay()
        }
    }
    var contentFrame :CTFrame? = nil
    var content      :NSAttributedString?{
        didSet{
            self.setNeedsLayout()
            self.setNeedsDisplay()
        }
    }
    override func layoutSubviews() {
        super.layoutSubviews();
        guard let content = self.content else { return }
        let setterRef:CTFramesetter = CTFramesetterCreateWithAttributedString(content)
        let pathRef :CGPath = CGPath(rect: self.bounds,transform: nil)
        let frameRef :CTFrame = CTFramesetterCreateFrame(setterRef, CFRangeMake(0, content.length), pathRef, nil);
        self.contentFrame = frameRef
    }
    override func draw(_ rect: CGRect) {
        if let ctx = UIGraphicsGetCurrentContext(){
            if let myrect = self.newRect{
                self.backgroundColor = UIColor.clear
                UIColor(hex: moya.bookSet.theme.themeColor).setFill()
                UIRectFill(rect)
                
                if let contentFrame = self.contentFrame{
                    ctx.textMatrix = .identity
                    ctx.translateBy(x: 0, y: self.bounds.height)
                    ctx.scaleBy(x: 1, y: -1)
                    CTFrameDraw(contentFrame, ctx)
                }
                
                let rec = myrect.intersection(rect);
                UIColor.clear.setFill()
                UIRectFill(rec)
            }else{
                guard let contentFrame = self.contentFrame else { return }
                ctx.textMatrix = .identity
                ctx.translateBy(x: 0, y: self.bounds.height)
                ctx.scaleBy(x: 1, y: -1)
                CTFrameDraw(contentFrame, ctx)
            }
        }
    }

}
